package com.jhx.mall.dao.impl;

import com.jhx.mall.dao.BaseDao;
import com.jhx.mall.dao.DtsAddressDao;
import com.jhx.mall.entity.DtsAddress;
import com.jhx.mall.entity.DtsGroupon;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DtsAddressDaoImpl extends BaseDao implements DtsAddressDao {

    //查询地址
    @Override
    public List<DtsAddress> selectAddress(int userId) {
        List<DtsAddress> list = new ArrayList<>();
        String sql = "select a.name as aname,r.name as provinceName,e.name as cityName,g.name as areaName,mobile,province_id,city_id,area_id,address\n" +
                "from dts_address a inner join dts_region r \n" +
                "on a.province_id = r.id inner join dts_region e\n" +
                "on a.city_id = e.id inner join dts_region g\n" +
                "on a.area_id = g.id\n" +
                "where user_id = ?";
        rs = super.executeQuery(sql, userId);
        try {
            while (rs.next()) {
                DtsAddress a = new DtsAddress();
                a.setName(rs.getString("aname"));
                a.setProvinceName(rs.getString("provinceName"));
                a.setCityName(rs.getString("cityName"));
                a.setAreaName(rs.getString("areaName"));
                a.setMobile(rs.getString("mobile"));
                a.setProvinceId(rs.getLong("province_id"));
                a.setCityId(rs.getLong("city_id"));
                a.setAreaId(rs.getLong("area_id"));
                a.setAddress(rs.getString("address"));
                list.add(a);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            super.closeAll(rs, pstmt, conn);
        }
        return list;
    }

    @Override
    public DtsAddress selectAddressDetail(int id) {
        return null;
    }

    //新建地址
    @Override
    public int addAddress(DtsAddress address) {
        String sql = "insert into dts_address(user_id,province_id,city_id,area_id,address,mobile,name,is_default,add_time,update_time) values(?,?,?,?,?,?,?,?,now(),now())";
        return super.executeUpdate(sql, address.getUserId(),address.getProvinceId(),address.getCityId(),address.getAreaId(),address.getAddress(),address.getMobile(),address.getName(),address.getIsDefault());
    }
    //修改地址
    @Override
    public int upAddress(DtsAddress address) {
        String sql = "update dts_address set province_id = ?,city_id = ?,area_id = ?,address = ?,mobile = ?,name = ?,is_default = ?,update_time = now() where id = ?";
        return super.executeUpdate(sql, address.getProvinceId(),address.getCityId(),address.getAreaId(),address.getAddress(),address.getMobile(),address.getName(),address.getIsDefault(),address.getId());
    }
    //删除地址
    @Override
    public int delAddress(int id) {
        String sql = "update dts_address set deleted = 1 where id = ?";
        return super.executeUpdate(sql, id);
    }
}
